package com.study.leetcode;

public class Solution_43 {
    public static String multiply(String num1, String num2) {
        if ("0".equals(num1)|| "0".equals(num2)){
            return "0";
        }
        int len1 = num1.length();
        int len2 = num2.length();
        int add;
        int cur;
        StringBuilder result = new StringBuilder();
        StringBuilder suffix0 = new StringBuilder();

        for (int i = len1 - 1; i >= 0; i--) {
            StringBuilder s = new StringBuilder();
            char c1 = num1.charAt(i);
            add = 0;
            for (int j = len2 - 1; j >= 0; j--) {
                char c2 = num2.charAt(j);
                cur = (c1 - '0') * (c2 - '0') + add;
                add = cur / 10;
                cur = cur % 10;
                s.append(cur);
            }
            if (add != 0) {
                s.append(add);
            }
            s.reverse().append(suffix0);
            result = new StringBuilder(add(result.toString(), s.toString()));
            suffix0.append("0");
        }
        return result.toString();
    }

    public static String add(String num1, String num2) {
        int idx1 = 0;
        int idx2 = 0;
        int len1 = num1.length();
        int len2 = num2.length();
        int add = 0;
        int cur;
        StringBuilder s = new StringBuilder();
        while (idx1 < len1 || idx2 < len2) {
            char c1 = idx1 < len1 ? num1.charAt((len1 - 1) - idx1++) : '0';
            char c2 = idx2 < len2 ? num2.charAt((len2 - 1) - idx2++) : '0';
            cur = (c1 - '0') + (c2 - '0') + add;
            add = cur / 10;
            cur = cur % 10;
            s.append(cur);
        }
        if (add != 0) {
            s.append(add);
        }
        return s.reverse().toString();
    }

    public static void main(String[] args) {
        String multiply = multiply("0", "111");
        System.out.println("multiply = " + multiply);
    }
}
